/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-09-02 22:42:44
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-09-03 22:51:26
 * @FilePath: /metaverse-manage/app/service/User.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Service } from 'egg';

export default class UserService extends Service {
  async queryAllUsers() {
    const result = await this.app.mysql.query('select id,openid,phone,nick_name,gender,avatar,mesh from sys_user');
    return result;
  }

  async countAllUsers() {
    const result = await this.app.mysql.query('select count(id) as count from sys_user');
    return result[0];
  }


  async queryUserById(id: number) {
    const result = await this.app.mysql.query(`select id,openid,phone,nick_name,gender,avatar,path,mesh from sys_user where id = '${id}'`);
    // const result = await this.app.mysql.get('sys_user', { id });
    return result[0];
  }

  async queryUserByOpenid(openid: string) {
    const result = await this.app.mysql.query(`select id,openid,phone,nick_name,gender,avatar,path,mesh from sys_user where openid ='${openid}'`);
    // const result = await this.app.mysql.get('sys_user', { id });
    return result[0];
  }

  async queryUserByPhone(phone: string) {
    const result = await this.app.mysql.query(`select id,openid,phone,nick_name,gender,avatar,path,mesh from sys_user where phone ='${phone}'`);
    // const result = await this.app.mysql.get('sys_user', { id });
    return result[0];
  }

  async createUser(user) {
    const result = await this.app.mysql.insert('sys_user', user);
    return result;
  }

  async updateUser(id, user) {
    const result = await this.app.mysql.update('sys_user', user, {
      where: { id },
    });
    return result;
  }
  async removeUser(id: number) {
    const result = await this.app.mysql.delete('sys_user', { id });
    return result;
  }

  async queryAllUsersByPage({ pageSize, page, ...condition }: any) {
    let sql = 'SELECT * FROM sys_user';
    const list = Object.entries(condition || {}).map(([key, value]) => {
      return `${key} LIKE '%${value}%'`;
    });
    if (list.length) {
      sql = `${sql} WHERE ${list.join(' AND ')}`;
    }
    const offset = (page - 1) * pageSize;
    sql = `${sql} LIMIT ${pageSize} OFFSET ${offset}`;
    const result = await this.app.mysql.query(sql);
    return result;
  }
}
